package cn.kgc.springboot.vue.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.kgc.springboot.vue.response.ResponseResult;
import cn.kgc.springboot.vue.service.MailService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @author 课工场
 * @date 2024/12/20
 * @description   如何实现邮箱信息的发送  139
 *   to  接收人
 *   from  发送人
 *   title   邮件标题
 *   content   邮件内容  code
 */
@Service
public class MailServiceImpl implements MailService {

    @Resource
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String account;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public ResponseResult sendMessage(String to) {

        // 创建邮件
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        // 接收人
        simpleMailMessage.setTo(to);
        // 发送人
        simpleMailMessage.setFrom(account);
        // 设置邮件摘要
        simpleMailMessage.setSubject("数智教育验证码");
        // 邮件发送日期
        simpleMailMessage.setSentDate(new Date());


        // 邮件内容   code
        int code  = RandomUtil.randomInt(100000, 999999);
        simpleMailMessage.setText("[数智教育平台]您的验证码是:"+code+",三分钟有效...");

        // 存储邮箱验证码
        stringRedisTemplate.opsForValue().set(to,code+"",3, TimeUnit.MINUTES);

        // 发送邮件
        javaMailSender.send(simpleMailMessage);
        return ResponseResult.success().message("验证码发送成功");
    }
}
